package com.tssm.core.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tssm.cache.memcached.TsSessionUtil;
import com.tssm.pojo.SarcSupplier;

public class UserFilter implements Filter {
	protected FilterConfig filterConfig = null;

	private String redirectURL = null;

	private List notCheckURLList = new ArrayList();

	private String sessionKey = null;

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		long userId = 0;
		SarcSupplier loginsupplier = TsSessionUtil.getTsUser(request);
		if (loginsupplier != null) {
			userId = loginsupplier.getSupplierid();
		}
		if (sessionKey == null) {
			filterChain.doFilter(request, response);
			return;
		}
		if ((!checkRequestURIIntNotFilterList(request)) && userId == 0) {
			response.sendRedirect("/index.do");
			return;
		}
		if (userId != 0) {

		} else {
			response.sendRedirect("/index.do");
			return;
		}
		if ((!checkRequestURIIntNotFilterList(request)) && userId == 0) {
			response.sendRedirect(redirectURL);
			return;
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {
		notCheckURLList.clear();
	}

	private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
		String uri = request.getServletPath()
				+ (request.getPathInfo() == null ? "" : request.getPathInfo());

		String s = uri.substring(uri.length() - 4, uri.length());
		if (s.equals(".jsp")) {
			return notCheckURLList.contains(uri);
		} else {
			return true;
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		redirectURL = filterConfig.getInitParameter("redirectURL");
		sessionKey = filterConfig.getInitParameter("checkSessionKey");
		String notCheckURLListStr = filterConfig
				.getInitParameter("notCheckURLList");
		if (notCheckURLListStr != null) {
			StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");
			notCheckURLList.clear();
			while (st.hasMoreTokens()) {
				notCheckURLList.add(st.nextToken());
			}
		}
	}
}
